package commons.base.http.example;

import java.io.IOException;

import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;

/**
 * websocket消息处理(非线程安全)，使用jetty的线程池，不需要自己再搞业务线程池
 * @author cihang.yuan
 *
 */
@WebSocket
public class DefaultWebSocket {
	
	@OnWebSocketConnect
	public void onConnect(Session session){
		System.err.println("[onConnect]" + session.getRemoteAddress());
	}
	
	@OnWebSocketClose
	public void onClose(Session session, int statusCode, String reason){
		System.err.println("onClose" + session.getRemoteAddress() + "," + statusCode + "," + reason);
	}

	// public void methodName(Session session, byte buf[], int offset, int length)
	@OnWebSocketMessage
	public void onMessage(Session session, String text){
		System.err.println("[onMessage]["+Thread.currentThread()+"]" + session.getRemoteAddress() + " : " + text);
		
		try {
			session.getRemote().sendString("hello world");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@OnWebSocketError
	public void onError(Session session, Throwable error){
		System.err.println("[onError]" + session.getRemoteAddress() + " : " + error.getMessage());
		error.printStackTrace();
	}

}
